import React, { Component } from 'react';
import PropTypes from 'prop-types'
import { Form, Input, InputNumber, Radio, Modal, Cascader, Row, Col, DatePicker, Table, Select, Button, Tooltip, Icon } from 'antd'
import moment from 'moment'
import Toggles from '../../components/Toggles'
import styles from './Form.less'
const RadioGroup = Radio.Group;
const FormItem = Form.Item
const InputGroup = Input.Group;
const Option = Select.Option;
import {   Popconfirm } from 'antd';

class EditableCell extends React.Component {
  state = {
    value: this.props.value,
    editable: false,
  }
  handleChange = (e) => {
    const value = e.target.value;
    this.setState({ value });
  }
  check = () => {
    this.setState({ editable: false });
    if (this.props.onChange) {
      this.props.onChange(this.state.value);
    }
  }
  edit = () => {
    this.setState({ editable: true });
  }
  render() {
    const { value, editable } = this.state;
    return (
      <div className="editable-cell">
        {
          editable ?
            <div className="editable-cell-input-wrapper">
              <Input
                value={value}
                onChange={this.handleChange}
                onPressEnter={this.check}
              />
              <Icon
                type="check"
                className="editable-cell-icon-check"
                onClick={this.check}
              />
            </div>
            :
            <div className="editable-cell-text-wrapper">
              {value || ' '}
              <Icon
                type="edit"
                className="editable-cell-icon"
                onClick={this.edit}
              />
            </div>
        }
      </div>
    );
  }
}
class CustomerForm extends Component {

  constructor(props) {
    super(props);
    this.state = {
    filterDropdownVisible: false,
    searchText: '',
    filtered: false,
  };

const  onInputChange = (e) => {
     this.setState({ searchText: e.target.value });
   }
const   onSearch = () => {
     const { searchText } = this.state;
     const reg = new RegExp(searchText, 'gi');
     this.setState({
       filterDropdownVisible: false,
       filtered: !!searchText,
       data: data.map((record) => {
         const match = record.name.match(reg);
         if (!match) {
           return null;
         }return {
          ...record,
          name: (
            <span>
              {record.name.split(reg).map((text, i) => (
                i > 0 ? [<span className="highlight">{match[0]}</span>, text] : text
              ))}
            </span>
          ),
        };
      }).filter(record => !!record),
    });
  }
  this.columns = [
    {
      title: '起始人数',
      dataIndex: 'name',
      filterDropdown: (
        <div className="custom-filter-dropdown">
          <Cascader
           placeholder='筛选'
           size='large'
           showSearch
           style={{marginTop:'6px'}}
           ref={ele => this.searchInput = ele}
           placeholder="Search name"
           value={this.state.searchText}
           onChange={this.onInputChange}
           onPressEnter={this.onSearch}
           options={[
                    {value:'主险',label:'主险'},
                    {value:'医疗险',label:'医疗险'},
                    {value:'家属医疗险',label:'家属医疗险'},
                    {value:'子女医疗险',label:'子女医疗险'},
                    {value:'配偶医疗险',label:'配偶医疗险'},
                    {value:'交通险',label:'交通险'},
                    {value:'意外医疗险',label:'意外医疗险'},
                    {value:'意外住院津贴险',label:'意外住院津贴险'},
                    {value:'住院津贴险',label:'住院津贴险'},
                    {value:'重大疾病险',label:'重大疾病险'},
                    {value:'女工生育险',label:'女工生育险'},
                    {value:'误工费',label:'误工费'},
                    {value:'雇主/异地',label:'雇主/异地'},
                    {value:'2商保',label:'2商保'},
                    {value:'雇主/商保',label:'雇主/商保'},

                  ]}
            />
            <Button type="primary" onClick={this.onSearch}>筛选</Button>
        </div>
      ),
      filterIcon: <Icon type="smile-o" style={{ color: this.state.filtered ? '#108ee9' : '#aaa' }} />,

      render: (text, record) => (
        <EditableCell
          value={text}
          onChange={this.onCellChange(record.key, 'price')}
        />
      ),
    }, {
      title: '截止人数',
      dataIndex: 'age',
    }, {
      title: '价格',
      dataIndex: 'price',
    }, {
      title: '成本',
      dataIndex: 'cost',
    },{
      title: '描述',
      dataIndex: 'serviceDescription',
    },{
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        return (
          this.state.dataSource.length > 1 ?
          (
            <Popconfirm title="确定要删除吗？" onConfirm={() => this.onDelete(record.key)}>
              <a href="#">Delete</a>
            </Popconfirm>
          ) : null
        );
      },
    }
  ];

  this.state = {
    index:0,
    visible: false,
     dataSource: [{
       key: '0',
       name: 'Edward King 0',
       age: '32',
       price: '价 格',
       cost:'成 本',
       serviceDescription: '服务描述London, Park Lane no. 0',
     }, {
       key: '1',
       name: 'Edward King 1',
       age: '32',
       address: 'London, Park Lane no. 1',
     }],
     count: 2,
   };

  this.columns1 = [{
  title: '服务子项名称',
  dataIndex: 'genre',
  width: '15%',
  render: (text, record) => (
    <EditableCell
      value={text}
      onChange={this.onCellChange(record.key1, 'genre')}
    />
  ),
}, {
  title: '服务子项类型',
  dataIndex: 'genre',
}, {
  title: '报销比例',
  dataIndex: 'reimburementRatio',
}, {
  title: '保额',
  dataIndex: 'insuredAmount',
},{
  title: '免赔额',
  dataIndex: 'deductible',
},{
  title: '每天补贴金额',
  dataIndex: 'subsidyAmount',
}, {
  title: '免赔期，天数',
  dataIndex: 'numberDayIndemnity',
}, {
  title: '日限额',
  dataIndex: 'quota',
},{
  title: '描述',
  dataIndex: 'description',
},{
  title: '操作',
  dataIndex: 'operation',
  render: (text, record) => {
    return (
      this.state1.dataSource1.length > 1 ?
      (
        <Popconfirm title="确定要删除吗？" onConfirm={() => this.onDelete1(record.key1)}>
          <a href="#">Delete</a>
        </Popconfirm>
      ) : null
    );
  },
}];


   this.state1 = {
     index:0,
     visible: false,
      dataSource1: [{
        key1: '0',
        genre:'服务子项类型',
        reimburementRatio: '报销比例',
        insuredAmount:'保额',
        deductible:'免赔额',
        subsidyAmount:'每天补贴金额',
        numberDayIndemnity:'免赔期，天数',
        quota:'日限额',
        description: '服务描述London, Park Lane no. 0',
      }, {
        key: '1',
        name: 'Edward King 1',
        age: '32',
        address: 'London, Park Lane no. 1',
      }],
      count1: 2,
    };
 }

 onCellChange = (key, dataIndex) => {
    return (value) => {
      const dataSource = [...this.state.dataSource];
      const target = dataSource.find(item => item.key === key);
      if (target) {
        target[dataIndex] = value;
        this.setState({ dataSource });
      }
    };
  }
  //删除
  onDelete = (key) => {
    const dataSource = [...this.state.dataSource];
    this.setState({ dataSource: dataSource.filter(item => item.key !== key) });
  }

  onDelete1 = (key1) => {
    const dataSource1 = [...this.state1.dataSource1];
    this.setState({ dataSource1: dataSource1.filter(item => item.key1 !== key1) });
  }
  //添加一行
  handleAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count,
      name: `Edward King ${count}`,
      age: 32,
      address: `London, Park Lane no. ${count}`,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
  }
  handleAdd1 = () => {
    const { count1, dataSource1 } = this.state1;
    const newData1 = {
      key: count1,
      name: `Edward King ${count1}`,
      age: 32,
      address: `London, Park Lane no. ${count1}`,
    };
    this.setState({
      dataSource1: [...dataSource1, newData1],
      count1: count1 + 1,
    });
  }


  onChange = (e) => {
     console.log('radio checked', e.target.value);
     this.setState({
       value: e.target.value,
     });
   }

  showModalHandler = (e) => {
      if (e) e.stopPropagation();
    this.setState({
      visible: true,
    });
  };

  hideModalHandler = () => {
    this.setState({
      visible: false,
    });
  };

//-----------------

//-----------------
handlerPre = () => {
  if(this.state.index>=0){
    this.setState({
      index:--this.state.index,
    })
  }
}

handlerNext = () => {
  if(this.state.index<=this.props.data.length){
    this.setState({
      index:++this.state.index,
    })
  }
}

handlerFirst = () => {
  this.setState({
    index:0,
  })
}

handlerLast = () => {
  this.setState({
    index:this.props.data.length-1,
  })
}
handlerPageChange = (page,pageSize) =>{
  this.setState({
    index:(page-1)*pageSize,
  })
}

  okHandler = () => {
    const { onOk } = this.props;
    this.props.form.validateFields((err, values) => {
      values.id = this.props.record.id;
      values.customerId && (values.customerId = values.customerId[0]);
      values.product && (values.price = values.product[0]);
      values.status && (values.status = values.status[0]);
      values.ladderQuotation && (values.ladderQuotation = values.ladderQuotation[0]);
      values.operator = localStorage.getItem('userName')||'';
      if (!err) {
        onOk(values);
        this.hideModalHandler();
      }
    });
  };



  render() {
    const { dataSource} = this.state;
    const {dataSource1} = this.state1;
    const columns = this.columns;
    const columns1 = this.columns1;
    const { children } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { id, customerNum,customer_name, price, cost, serviceDescription,priceTerms,
       effectiveTime,status,fax, ladderQuotation,createTime,operator,product,deadTime,modifyTime} = this.props.record || {};
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      colon:false
    };



    // (<InputGroup compact>
    //    <Select defaultValue="客户名称">
    //      <Option value="1">海世深信息科技有限公司</Option>
    //      <Option value="2">上海出颖信息技术有限公司</Option>
    //      <Option value="3">北京蓝海时代国际企业管理顾问有限公司</Option>
    //      <Option value="4">道奇（福建）制鞋有限公司</Option>
    //      <Option value="5">佩雷罗贸易（上海）有限公司</Option>
    //      <Option value="6">上海翼汇投资咨询有限公司</Option>
    //      <Option value="7">上海易靓贸易有限公司</Option>
    //      <Option value="8">上海哈喽实业有限公司</Option>
    //      <Option value="9">芊景（上海）企业管理咨询有限公司</Option>
    //      <Option value="10">玻儿（福建）化妆品有限公司</Option>
    //      <Option value="11">上海阿里宝宝婴儿用品有限公司</Option>
    //      <Option value="12">上海同舟服饰发展有限公司</Option>
    //      <Option value="13">晶玺商贸（上海）有限公司</Option>
    //      <Option value="14">上海方寸信息科技有限公司</Option>
    //      <Option value="15">上海友纳康财务咨询有限公司</Option>
    //      <Option value="16">上海庞克广告有限公司</Option>
    //      <Option value="17">上海迪凯标识科技有限公司</Option>
    //      <Option value="18">北京瑞友科技股份有限公司</Option>
    //      <Option value="19">上海捷融电子商务有限公司</Option>
    //      <Option value="20">上海久事机械电子有限公司</Option>
    //      <Option value="21">武汉绿色网络信息服务有限责任公司</Option>
    //      <Option value="22">上海钦州环保经营服务部</Option>
    //      <Option value="23">上海通联银华支付网络服务有限公司</Option>
    //      <Option value="24">裕程（昆山）体育用品有限公司</Option>
    //      <Option value="25">上海虹创工贸有限公司</Option>
    //      <Option value="26">联华超市股份有限公司</Option>
    //      <Option value="27">管家壹佰（北京）科技有限公司</Option>
    //      <Option value="28">苏州凯华世家酒店管理有限公司</Option>
    //    </Select>
    // </InputGroup>)



    const onRowClick = (record) => {
        // console.log('onRowClick:',record);
        let i = 0;
        for(i;i<data.length;i++){
          if(data[i].id===record.id){
            // index = i;
            break;
          }
        }
        this.setState({
          index:i,
        })
      }

  return (
    <span>
      <span onClick={this.showModalHandler}>
        { children }
      </span>
    <Modal
      visible={this.state.visible}
      onOk={this.okHandler}
      onCancel={this.hideModalHandler}
      Style={{}}
    width='60vw'
    >
    <Form  layout="horizontal"  nSubmit={this.okHandler}>
    <Toggles name='报价单'>
     <Row >
     <Col span={10} style={{lineHeight:30}}>
     <FormItem label='客户名称' {...formItemLayout}>
     {
           getFieldDecorator('customer_name',{
             initialValue: customer_name,
           })(<Input size='small' placeholder=''/>)
       }
     </FormItem>
       <FormItem label='价格' {...formItemLayout}>
         {
           getFieldDecorator('price',{
             initialValue:price,
           })( <InputNumber min={0} max={1000} step={20.00} size='small' style={{width:'100%'}}/>)
         }
       </FormItem>
       <FormItem label='服务描述' {...formItemLayout}>
         {
           getFieldDecorator('serviceDescription',{
             initialValue:serviceDescription,
           })(<Input size='small' type='textarea'/>)
         }
       </FormItem>
       <FormItem label='失效时间' {...formItemLayout}>
         {
           getFieldDecorator('deadTime',{
             initialValue:deadTime
           })(<DatePicker size='small' placeholder='' style={{width:'100%'}}/>)
         }
       </FormItem>
       <FormItem
      {...formItemLayout}
       label='阶梯报价'
     >
     {
       getFieldDecorator('ladderQuotation', {
       initialValue: ladderQuotation,
         rules: [{ required: true, message: '请选择阶梯报价!' }],
     })(
       <RadioGroup >
         <Radio value='1'>人 均</Radio>
         <Radio value='2'>总 价</Radio>
         <Radio value='0'>无</Radio>
       </RadioGroup>
       )
     }

     </FormItem>


      </Col>
    <Col span={10} style={{lineHeight:30}}>
        <FormItem label='产品' {...formItemLayout}>
          {
            getFieldDecorator('product',{
              initialValue:product,
                rules: [{ required: true, message: '请输入产品名称!' }],
            })(<InputGroup compact>
               <Select defaultValue="产品名称">
                 <Option value="个税">个税</Option>
                 <Option value="体检">体检</Option>
                 <Option value="员工慰问">员工慰问</Option>
                 <Option value="委托服务费">委托服务费</Option>
                 <Option value="工资代收代付">工资代收代付</Option>
                 <Option value="工资服务费服">工资服务费服</Option>
                 <Option value="服装费">服装费</Option>
                 <Option value="服务费">服务费</Option>
                 <Option value="档案">档案</Option>
                 <Option value="证件工本费">证件工本费</Option>
                 <Option value="银行转账费">银行转账费</Option>
                 <Option value="工资营业税">工资营业税</Option>

               </Select>
            </InputGroup>)
          }
        </FormItem>
        <FormItem label='成本' {...formItemLayout}>
          {
            getFieldDecorator('cost',{
              initialValue:cost,
            })(<InputNumber min={0} max={1000} step={20.00} size='small' style={{width:'100%'}}/>)
          }
        </FormItem>
        <FormItem label='生效时间' {...formItemLayout}>
          {
            getFieldDecorator('effectiveTime',{
              initialValue: effectiveTime
            })(<DatePicker size='small' placeholder='' style={{width:'100%'}}/>)
          }
        </FormItem>
        <FormItem
         {...formItemLayout}
          label='状态'
        >
        {
          getFieldDecorator('status', {
          initialValue: status,
            rules: [{ required: true, message: '请选择状态!' }],
        })(
            <RadioGroup defaultValue={1}>
              <Radio value='1'>有 效</Radio>
              <Radio value='2'>失 效</Radio>
            </RadioGroup>
          )
        }

        </FormItem>
        <FormItem
        {...formItemLayout}
          label='报价方式'
        >
          {
            getFieldDecorator('priceTerms', {
            initialValue: priceTerms,
            rules: [{ required: true, message: '请选择报价方式!' }],
          })(
              <RadioGroup>
                <Radio value='1'>年</Radio>
                <Radio value='2'>月</Radio>
              </RadioGroup>
            )
          }
        </FormItem>

      </Col>
      </Row>
      </Toggles>

      </Form>
        <span className={styles.navButton}  style={{ marginRight: 10}}>
          <Tooltip overlayClassName={styles.tooltip} title='第一条'><Button size='small' onClick={this.handlerFirst}><Icon type="backward" /></Button></Tooltip>
          <Tooltip overlayClassName={styles.tooltip} title='上一条'><Button size='small' onClick={this.handlerPre}><Icon type="caret-left" /></Button></Tooltip>
          <Tooltip overlayClassName={styles.tooltip} title='下一条'><Button size='small' onClick={this.handlerNext}><Icon type="caret-right" /></Button></Tooltip>
          <Tooltip overlayClassName={styles.tooltip} title='最后一条'><Button size='small' onClick={this.handlerLast}><Icon type="forward" /></Button></Tooltip>
        </span>
        <span  style={{ marginRight: 441}}>
          <Button style={{ marginRight: 5}} onClick={this.handleAdd}>添 加</Button>
          <Button style={{ marginRight: 5}} onClick={this.onDelete}>删 除</Button>
          <Button >撤 销</Button>
        </span>

          <span className={styles.navButton} style={{ marginRight: 10}}>
            <Tooltip overlayClassName={styles.tooltip} title='第一条'><Button size='small' onClick={this.handlerFirst}><Icon type="backward" /></Button></Tooltip>
            <Tooltip overlayClassName={styles.tooltip} title='上一条'><Button size='small' onClick={this.handlerPre}><Icon type="caret-left" /></Button></Tooltip>
            <Tooltip overlayClassName={styles.tooltip} title='下一条'><Button size='small' onClick={this.handlerNext}><Icon type="caret-right" /></Button></Tooltip>
            <Tooltip overlayClassName={styles.tooltip} title='最后一条'><Button size='small' onClick={this.handlerLast}><Icon type="forward" /></Button></Tooltip>
          </span>
            <Button style={{ marginRight: 5}} onClick={this.handleAdd1}>添 加</Button>
            <Button style={{ marginRight: 5}} >删 除</Button>
            <Button style={{ marginRight: 5}} >撤 销</Button>

            <div>
            <Row>
          <Col span={12} >
          <Table
            bordered size="middle"
            pagination={{ pageSize: 50 }}
            style={{ marginRight: 15}}
            scroll={{ y: 240 }}
            dataSource={dataSource}
            columns={columns}
          />
          </Col>
            <Col span={12}>
            <Table
              bordered size="middle"


              scroll={{ x: 1000,y:240}}
              pagination={{ pageSize: 50 }}
              style={{ marginRight: 15}}
              dataSource={dataSource1}
              columns={columns1}
            />
            </Col>
          </Row>
            </div>
      </Modal>

      </span>
      );
      }
      }
      export default Form.create()(CustomerForm);
